package net.wanho.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    private static final String SECRET = "wanho";
    private static final int EXPIRE = 12;

    /**
     * 生成令牌
     */
    public static String generate(Map<String, Object> payload){
        Calendar c = Calendar.getInstance();
        c.add(Calendar.HOUR, EXPIRE);

        String token = JWT.create()
                .withPayload(payload) // 载荷
                .withExpiresAt(c.getTime()) // 过期时间
                .sign(Algorithm.HMAC256(SECRET)); // 签名：算法和密钥
        return token;
    }

    /**
     * 校验令牌
     *  如果令牌过期，会抛异常TokenExpiredException
     *  一般会返回boolean，表示校验是否通过
     */
    public static boolean valid(String token){
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (Exception e) {
           return false;
        }
    }

    /**
     * 解析令牌
     *  如果令牌过期，会抛异常TokenExpiredException
     */
    public static Integer parseInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static String parseString(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }
}
